package com.cy.pj.common.web.domain;

import com.cy.pj.common.utils.SqlUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class BaseController {

    public <T>Page<T> startPage(Class<T> tClass){
        // 获得request对象,response对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        String pageSizeStr = request.getParameter("pageSize");
        String pageCurrent = request.getParameter("pageCurrent");
        if(pageCurrent == null){
            pageCurrent = "1";
        }
        if(pageSizeStr == null){
            pageSizeStr = "0";
        }
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        if( pageSize==0){
            pageSize =5;
        }
        Integer pageNum = Integer.parseInt(request.getParameter("pageCurrent"));
        String orderByColumn = request.getParameter("orderByColumn");
        if(StringUtil.isEmpty(orderByColumn)){
            orderByColumn = "order by id desc";
        }
        Page<T> page = null;
        if (StringUtil.isNotEmpty(pageNum+"") && StringUtil.isNotEmpty(pageSize+""))
        {
            String orderBy = SqlUtil.escapeOrderBySql(orderByColumn);
            page  = PageHelper.startPage(pageNum, pageSize, orderBy);
            page.setPageNum(pageNum);
            page.setPageSize(pageSize);
        }
        return page;
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


}
